import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/login/config_model.dart';
import 'package:hktk_app/model/my/app_list_model.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/mine/customer_expandable_widget.dart';
import 'package:hktk_app/widget/page_title_widget.dart';
import 'package:url_launcher/url_launcher.dart';

/// 在线客服页面
class CustomerServicePage extends StatefulWidget {
  const CustomerServicePage({super.key});

  @override
  State<CustomerServicePage> createState() => _CustomerServicePageState();
}

class _CustomerServicePageState extends State<CustomerServicePage> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 常见问题相关数据
  late List<AppListModel> _list;

  late ConfigModel? _configModel;

  @override
  void initState() {
    super.initState();
    debugPrint("customerServicePage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _configModel = null;
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            child: _background(),
          ),
          Positioned(
            top: top + 88,
            left: 55,
            child: _backgroundImg(),
          ),
          Positioned.fill(
            child: _stateContent(),
          ),
        ],
      ),
    );
  }

  /// 背景色实现
  _background() {
    double width = MediaQuery.of(_context).size.width;
    return Image.asset(
      "images/my/customer_service_bg.png",
      width: width,
      fit: BoxFit.fitWidth,
    );
  }

  /// 背景图片
  _backgroundImg() {
    return Image.asset(
      "images/my/customer_service_image.png",
      width: 125,
      // height: 212,
    );
  }

  /// 内容显示
  _stateContent() {
    return SafeArea(child: Column(
      children: [
        PageTitleWidget(
          name: "在线客服",
          pageContext: _context,
          backgroundColor: Colors.transparent,
        ),
        Expanded(child: _futureData()),
      ],
    ));
  }

  /// 加载初始化方法
  _futureData() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      _list = await MyDao.appList();

      // 获取相关配置信息
      _configModel = await LoginDao.config();

      map["suc"] = true;
    } catch (e) {
      debugPrint("customerServicePage 页面 -> _initData 方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("customerServicePage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 具体内容显示方法
  _content() {
    var bottom = MediaQuery.of(_context).padding.bottom;
    return Container(
      margin: EdgeInsets.only(left: 30, right: 30, bottom: bottom),
      child: Column(
        children: [
          hiSpace(height: 40),
          _serviceItems(),
          hiSpace(height: 35),
          _problemItems(),
        ],
      ),
    );
  }

  /// 服务组件
  _serviceItems() {
    return Container(
      width: 1.sw-180,
      // right 70
      margin: EdgeInsets.only(left: 180, right: 0),
      child: Column(
        children: [

          hiSpace(height: 2),
          Text(
            "有问题，找客服",
            style: FontUtil.fontGrey1(20),
          ),
          hiSpace(height: 30),
          _btnItem(),
        ],
      ),
    );
  }

  /// 按钮组件
  _btnItem() {
    return GestureDetector(
      onTap: _onTapFunLjzx,
      child: Container(
        // width: 276,
        decoration: BoxDecoration(
          color: colorBlue1,
          borderRadius: BorderRadius.all(Radius.circular(35)),
        ),
        child: Padding(
          padding: EdgeInsets.only(bottom: 8,top: 4),
          child: Center(
            child: Text(
              "立即咨询",
              style: FontUtil.fontWhile1(20, fontWeight: FontWeight.w500),
            ),
          ),
        ),
      ),
    );
  }

  /// 立即咨询按钮点击方法
  _onTapFunLjzx() {
    debugPrint("customerServicePage 页面 -> 你点击了 ===> 立即咨询");
    String url = _configModel?.appConfig?.customerServiceLink ?? "";
    if (url != "") {
      _launchWeiXin(url: url).then((Map<String, dynamic> map) {
        debugPrint("customerServicePage 页面 -> 跳转返回值 ===> $map");
        if (!map["suc"]) {
          ToastUtil.show(context: _context, msg: map["msg"]);
        }
      });
    } else {
      ToastUtil.show(context: _context, msg: "获取链接失败，请退出重试");
    }
  }

  Future<Map<String, dynamic>> _launchWeiXin({required String url}) async {
    Map<String, dynamic> map = {};
    try {
      bool cna = await canLaunchUrl(Uri.parse(url));
      if (cna) {
        await launchUrl(Uri.parse(url));
        map["suc"] = true;
      } else {
        map = {"suc": false, "msg": "未找到微信，请先安装微信"};
      }
    } catch (e) {
      debugPrint("customerServicePage 页面 -> 跳转微信立即咨询发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
    }
    return map;
  }

  /// 常见问题组件
  _problemItems() {
    return Container(
      height: _getListHeight(),
      padding: EdgeInsets.all(30),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "常见问题",
            style: FontUtil.fontBlack1(24, fontWeight: FontWeight.w500),
          ),
          hiSpace(height: 10),
          Expanded(child: _problemContentItem()),
        ],
      ),
    );
  }

  /// 计算内容高度方法
  double _getListHeight() {
    double height = MediaQuery.of(_context).size.height;
    var padding = MediaQuery.of(_context).padding;
    double max = height - 390 - padding.top - padding.bottom;
    double itemHeight = 0;
    if (_list.isNotEmpty) {
      int length = _list.length;
      itemHeight = length * 88 + (length - 1) * 20 + 128;
    }
    if (max < 648) {
      return max;
    }
    if (itemHeight < 648) {
      return 648;
    } else if (itemHeight < max) {
      return itemHeight;
    }
    return max;
  }

  /// 常见问题内容组件
  _problemContentItem() {
    if (_list.isNotEmpty) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.separated(
          itemBuilder: _itemBuilder,
          separatorBuilder: _separatorBuilder,
          itemCount: _list.length,
        ),
      );
    } else {
      return showNoData();
    }
  }

  /// 内容组件显示
  Widget? _itemBuilder(BuildContext context, int index) {
    AppListModel model = _list[index];
    return CustomerExpandableWidget(model: model, index: index + 1);
  }

  /// 间隔组件显示
  Widget _separatorBuilder(BuildContext context, int index) {
    return hiSpace(height: 20);
  }
}
